<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="customer" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="客户名称" prop="customer_name">
                    <el-input v-model="customer.customer_name" placeholder="客户名称" />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="客户编号" style="margin-bottom: 30px;">
                            <el-input v-model="customer.customer_code" placeholder="自动获取编号" disabled />
                        </el-form-item>
                        <el-form-item label="客户来源" prop="" style="margin-bottom: 30px;">
                            <el-input v-model="customer.customer_source" placeholder="客户来源" />
                        </el-form-item>
                        <el-form-item label="所属行业" prop="customer_industry" style="margin-bottom: 30px;">
                            <el-select v-model="customer.customer_industry" placeholder="请选择所属行业">
                                <el-option v-for="item in industryOptios" :key="item.dict_value"
                                    :label="item.dict_label" :value="item.dict_value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="customer_address" label="客户地址" style="margin-bottom: 30px;">
                            <el-input v-model="customer.customer_address" placeholder="客户地址" />
                        </el-form-item>

                        <el-form-item prop="dept_id" label="销售部门" style="margin-bottom: 30px;">
                            <el-tree-select v-model="customer.dept_id" :data="deptOptions" :props="defaultProps"
                                :check-strictly="true" placeholder="请选择销售部门" @change="getUser()">
                                <template #header>
                                    <el-input v-model="deptName" placeholder="搜索销售部门" style="padding: 5px"
                                        @input="getDeptDebounced" />
                                </template>
                            </el-tree-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="客户状态" prop="customer_status" style="margin-bottom: 30px;">
                            <el-select v-model="customer.customer_status" placeholder="请选择客户状态">
                                <el-option v-for="item in statusOptios" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="客户级别" style="margin-bottom: 30px;">
                            <el-rate v-model="customer.customer_level" :colors="colors" />
                        </el-form-item>
                        <el-form-item prop="customer_email" label="客户邮箱" style="margin-bottom: 30px;">
                            <el-input v-model="customer.customer_email" placeholder="客户邮箱" />
                        </el-form-item>
                        <el-form-item prop="customer_details" label="客户详情" style="margin-bottom: 30px;">
                            <el-input v-model="customer.customer_details" placeholder="客户详情" />
                        </el-form-item>
                        <el-form-item prop="customer_personCharge" label="销售负责人" style="margin-bottom: 30px;">
                            <el-select v-model="customer.customer_personCharge" placeholder="请选择销售负责人">
                                <template #header>
                                    <el-input v-model="userName" placeholder="搜索销售负责人" style="padding: 5px"
                                        @input="getUserDebounced" />
                                </template>
                                <el-option v-for="item in userOptions" :key="item.user_id" :label="item.user_name"
                                    :value="item.user_id" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">联系人信息</h2>
            <el-form ref="ruleFormRef1" style="max-width: 1200px;margin: 20px;" :model="customer" status-icon
                :rules="rules1" label-width="auto" class="demo-ruleForm">
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item prop="contacts_name" label="联系人姓名" style="margin-bottom: 30px;">
                            <el-input v-model="customer.contacts_name" placeholder="联系人姓名" />
                        </el-form-item>
                        <el-form-item label="联系人手机号" prop="contacts_phone" style="margin-bottom: 30px;">
                            <el-input v-model="customer.contacts_phone" placeholder="联系人手机号" />
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="联系人部门" prop="" style="margin-bottom: 30px;">
                            <el-input v-model="customer.contacts_dept" placeholder="联系人部门" />
                        </el-form-item>
                        <el-form-item prop="" label="联系人职务" style="margin-bottom: 30px;">
                            <el-input v-model="customer.contacts_position" placeholder="联系人职务" />
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <!-- <div class="section">
            <h2 class="section-title">上传附件</h2>
            <el-upload v-model:file-list="fileList" class="upload-demo" :auto-upload="false" action="#"
                :on-change="handleChange">
                <el-button type="primary">Click to upload</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        jpg/png files with a size less than 500kb
                    </div>
                </template>
</el-upload>
</div> -->

        <!-- 底部操作按钮 -->
        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, inject } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { debounce } from 'lodash';
import { useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';
export default {
    setup() {
        const customer = reactive({
            customer_name: "",//客户名称
            customer_code: "",//客户编号
            customer_status: "",//客户状态
            customer_source: "",//客户来源
            customer_level: "0",//客户级别
            customer_industry: "",//所属行业
            customer_email: "",//客户邮箱
            customer_address: "",//客户地址
            customer_details: "",//客户详情
            customer_personCharge: "",//销售负责人
            dept_id: "",//负责人部门
            contacts_name: "",//联系人姓名
            contacts_phone: "",//联系人电话
            contacts_dept: "",//联系人部门
            contacts_position: "",//联系人职务
        })
        const ruleFormRef = ref(null)
        const ruleFormRef1 = ref(null)
        const rules = reactive({
            customer_name: [
                { required: true, message: "客户名称不能为空", trigger: ['blur', 'change'] },
            ],
            customer_source: [
                { required: true, message: "客户来源不能为空", trigger: ['blur', 'change'] },
            ],
            customer_email: [
                { required: true, message: "客户邮箱不能为空", trigger: ['blur', 'change'] }
                ,
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
            ],
            customer_address: [
                { required: true, message: "客户地址不能为空", trigger: ['blur', 'change'] },
            ],
            customer_details: [
                { required: true, message: "客户详情不能为空", trigger: ['blur', 'change'] },
            ],
            customer_personCharge: [
                { required: true, message: "销售负责人不能为空", trigger: ['blur', 'change'] },
            ],
            dept_id: [
                { required: true, message: "销售负责人部门不能为空", trigger: ['blur', 'change'] },
            ],
            customer_status: [
                { required: true, message: "客户状态不能为空", trigger: ['blur', 'change'] },
            ],
            customer_industry: [
                { required: true, message: "客户所属行业不能为空", trigger: ['blur', 'change'] },
            ]
        });
        const rules1 = reactive({
            contacts_name: [
                { required: true, message: "联系人姓名不能为空", trigger: ['blur', 'change'] },
            ],
            contacts_phone: [
                { required: true, message: "联系人电话不能为空", trigger: ['blur', 'change'] },
            ],
            contacts_dept: [
                { required: true, message: "联系人部门不能为空", trigger: ['blur', 'change'] },
            ],
            contacts_position: [
                { required: true, message: "联系人职位不能为空", trigger: ['blur', 'change'] },
            ],
        })
        const router = useRouter()
        const statusOptios = ref([])
        const industryOptios = ref([])
        const deptOptions = ref([])
        const userOptions = ref([])
        const deptName = ref("")
        const userName = ref("")
        // const fileList = ref([])

        onMounted(() => {
            getDept()
            // getUser()
            getStatus()
            getIndustry()
        })

        function getStatus() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "customer_status"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                statusOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getIndustry() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "customer_industry"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                industryOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //防抖函数0.5秒后进行查询
        const getDeptDebounced = debounce(getDept, 500);
        function getDept() {
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                params: {
                    name: deptName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.dept_id,
                label: item.dept_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        const getUserDebounced = debounce(getUser, 500);
        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                params: {
                    dept: customer.dept_id,
                    name: userName.value
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        async function handleAdd() {
            const ruleForm = await ruleFormRef.value.validate().catch(() => false);
            const ruleForm1 = await ruleFormRef1.value.validate().catch(() => false);
            if (ruleForm && ruleForm1) {
                if (customer.customer_code == "") {
                    obtainCode().then(() => {
                        customerAdd()
                    }).catch((err) => {
                        console.info(err)
                    });
                } else {
                    customerAdd()
                }
            }
        }

        function customerAdd() {
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在添加中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            axios.post("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerAdd", {
                customer_name: customer.customer_name,
                customer_code: customer.customer_code,
                customer_status: customer.customer_status,
                customer_source: customer.customer_source,
                customer_level: customer.customer_level,
                customer_industry: customer.customer_industry,
                customer_email: customer.customer_email,
                customer_address: customer.customer_address,
                customer_details: customer.customer_details,
                customer_personCharge: customer.customer_personCharge,
                dept_id: customer.dept_id,
                del_flag: '0',
                create_by: localStorage.getItem('userLName'),
                create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                contacts_name: customer.contacts_name,
                contacts_phone: customer.contacts_phone,
                contacts_dept: customer.contacts_dept,
                contacts_position: customer.contacts_position
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '客户信息添加成功！'
                    });
                    handleClose()
                } else {
                    ElMessage({
                        type: 'danger',
                        message: '客户信息添加失败！'
                    });
                }
            }).catch((err) => {
                console.info(err)
            }).finally(() => {
                loadingInstance.close();
            })

        }

        function obtainCode() {
            return axios.get("http://localhost:5181/api/DJBH/DJBH", {
                params: {
                    en_code: 6
                }
            }).then((result) => {
                customer.customer_code = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        const handleClose = () => {
            const targetPath = "/main/Sinv/CustomerManagement";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "客户管理",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        };

        return {
            customer, statusOptios, industryOptios, deptOptions, userOptions, ruleFormRef, rules, handleAdd, handleClose, ruleFormRef1, rules1,
            getDeptDebounced, deptName, getUser, userName, getUserDebounced
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>